using System;
using System.Threading.Tasks;
using TMPro;
using UnityEngine;
using WolfCarol.AvgToolkit.Command;
using WolfCarol.AvgToolkit.Tween;
using WolfCarol.AvgToolkit.Save;
using System.Text.RegularExpressions;

namespace WolfCarol.AvgToolkit.Examples
{
    [Serializable]
    public class TextData
    {
        public string Name;

        public string Dialogue;

        public TextData()
        {
            Name = string.Empty;
            Dialogue = string.Empty;
        }
    }

    public class Typewriter : LinePresenter, ISavable<TextData>
    {
        [SerializeField] protected TMP_Text m_nameText;

        [SerializeField] protected TMP_Text m_dialogueText;

        public VariableManager variableManager;

        protected const float CharTime = 0.01f;

        protected string m_dialogue;

        public override async Task PresentLine(string name, string dialogue)
        {
            string pattern = @"\{.*?\}";
            foreach (Match match in Regex.Matches(name, pattern))
            {
                string replace = variableManager.GetString(match.Value.Trim('{', '}'));
                name = name.Replace(match.Value, replace);
            }
            m_nameText.text = name;
            foreach (Match match in Regex.Matches(dialogue, pattern))
            {
                string replace = variableManager.GetString(match.Value.Trim('{', '}'));
                dialogue = dialogue.Replace(match.Value, replace);
            }
            m_dialogue = dialogue;
            m_dialogueText.text = string.Empty;
            await m_dialogueText.DoText(m_dialogue, CharTime * dialogue.Length);
        }

        public void Clear()
        {
            m_nameText.text = string.Empty;
            m_dialogue = string.Empty;
            m_dialogueText.text = m_dialogue;
        }

        public TextData Save()
        {
            return new TextData()
            {
                Name = m_nameText.text,
                Dialogue = m_dialogue
            };
        }

        public void Load(TextData obj)
        {
            m_nameText.text = obj.Name;
            m_dialogue = obj.Dialogue;
            m_dialogueText.text = m_dialogue;
        }
    }
}
